/*
 * @Author: FanWeiHua
 * @Date: 2021-05-14 17:31:19
 * @LastEditTime: 2021-07-16 14:53:27
 * @Description: 开发模式下的node服务
 */
const app = require('./nodeServer/init'); // 初始化node服务
const path = require('path');
const os = require('os');
const open = require('open');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const portfinder = require('portfinder');
const { getIPAddress } = require('./common/util.js');
/**
 * webpack的自定义配置
 */
const webpackConfig = JSON.parse(process.env.webpackConfig);
/**
 * 执行开发模式服务
 */
const config = require('./webpack.dev.js');
const compiler = webpack(config);
/**
 * 资源的基础路径
 */
const publicPathName = webpackConfig.publicPath;

/**
 * 开发热更新中间件
 */
const devMiddleware = webpackDevMiddleware(compiler, {
  publicPath: publicPathName,
  stats: 'errors-only' // 不显示控制台打包信息
});
/**
 * 热更新
 */
const hotMiddleware = webpackHotMiddleware(compiler, {
  log: console.log,
  path: '/__webpack_hmr',
  heartbeat: 10 * 1000
});
app.use(hotMiddleware);
app.use(devMiddleware);
app.get('*', (req, res, next) => {
  const filename = path.join(__dirname, `../dist/${webpackConfig.project.name}`, 'index.html');
  compiler.outputFileSystem.readFile(filename, (err, result) => {
    if (err) {
      return next(err);
    }
    res.set('content-type', 'text/html');
    res.send(result);
    res.end();
  });
});
/**
 * 设置有效端口并且监听服务
 */
const setPortListen = async () => {
  portfinder.basePort = 8000;
  const port = await portfinder
    .getPortPromise()
    .then(port => {
      return port;
    })
    .catch(err => {
      console.log(err);
      return 8081;
    });
  app.listen(port, function () {
    // 获取ip地址
    const ipAddress = getIPAddress();
    const address = [`http://localhost:${port}${publicPathName}`];
    console.log('app listening on the following address:');
    console.log('\x1b[96m', `${address[0]}`);
    if (ipAddress) {
      address.push(`http://${ipAddress}:${port}${publicPathName}`);
      console.log('\x1b[95m', `${address[1]}`);
    }
    console.log('\x1bPlease wait while building . . .');
    open(address[address.length - 1], { wait: true });
  });
};
setPortListen(); // 设置有效端口并且监听服务
